import {
	defineStore
} from 'pinia'
import {
	reactive,
	ref,
	watch,
	computed
} from 'vue'
import {
	login,
	register
} from '@/api/api'
import { myRouter, 登录页 } from '@/utils/permission'
import * as util from '@/amtf/utils'

export default defineStore('user', () => {
	const userInfo = reactive({})

	const 展示用户名 = computed(() => userInfo?.nickName?.trim() || userInfo?.userName || userInfo?.phone)
	const hasLogin = computed(() => userInfo.token ? true : false)

	// 如果用computed ，异步获取远端图片时没法弄，只能得到promise
	const 展示用户头像 = computed(() => {
		let res = userInfo.avatar ? util.予图片路径(userInfo.avatar) : "/static/logo.png"
		return res
	})

	let 忽略监控 = false
	const 初始化 = () => {
		console.log('初始化ing: ');
		const res = uni.getStorageSync('userInfo')
		// console.log('初始化 res: ', res);
		if (res?.token) {
			console.log('缓存有值,忽略监控ing: ');
			忽略监控 = true
			// console.log('userInfo: ', userInfo);
			util.对象重予(userInfo, res)
			// console.log('userInfo: ', userInfo);
			忽略监控 = false
		}
	}
	初始化()

	const 清空 = () => {
		util.对象重予(userInfo, {})
		console.log('清空 忽略监控: ', 忽略监控);
	}

	const 要登录否 = () => {
		console.log('要登录否: hasLogin.value', hasLogin.value);
		if (!hasLogin.value) {
			uni.showModal({
				title: "登录后才能继续，要登么？",
				success: res => {
					if (res.confirm) {
						去登录()
					}
				}
			})
			return false
		};
		return true
	}

	const 去登录 = () => {
		let pages = getCurrentPages();
		let 当前页 = pages.at(-1)
		console.log('当前页: ', 当前页);
		let route = pages[pages.length - 1].route;
		console.log('route: ', route);
		console.log('登录页: ', 登录页);
		const url = 登录页 + '?next=/' + route
		console.log('url: ', url);
		uni.navigateTo({
			url
		})
	}

	const 登录 = async (req, next = '', 提示 = true) => {
		const res = await login(req)
		console.log('登录 res: ', res);
		if (res.code === 0) {
			let obj = {
				expiresAt: res.data.expiresAt,
				token: res.data.token,
				...res.data.user
			}
			util.对象重予(userInfo, obj)
			if (提示) {
				console.log('提示: ', 提示);
				uni.showToast({
					title: '登录成功😀',
				})
			}
			// console.log('next: ', next);
			if (next) {
				console.log('有 next: ', next);
				let pages = getCurrentPages();
				let 返回层数 = 0
				for (let i = pages.length - 1; i >= 0; i--) {
					let page = pages[i]
					console.log('page: ', page);
					if (("/" + page.route) == next) {
						break
					}
					返回层数++
				}
				setTimeout(() => {
					// uni.reLaunch({
					// 	url: next
					// })
					uni.navigateBack({
						delta: 返回层数
					});
				}, 400)
			}
			return res
		}
		uni.showToast({
			icon: 'none',
			title: res.msg,
			duration: 3000
		})
		return res
	}

	const 注册 = async (req, next = '') => {
		const res = await register(req)
		console.log('注册 res: ', res);
		if (res.code === 0) {
			uni.showToast({
				title: '注册成功🚀',
			})
			// console.log('next: ', next);
			// if (next) {
			// 	setTimeout(() => {
			// 		uni.reLaunch({
			// 			url: next
			// 		})
			// 	}, 400)
			// }
			return res
		}
		uni.showToast({
			icon: 'none',
			title: res.msg,
			duration: 3000
		})
		return res
	}

	const 退出登录 = () => {
		console.log('退出登录: ');
		uni.showModal({
			title: "确定要 退出登录 么？",
			success: res => {
				if (res.confirm) {
					清空()
				}
			}
		})
		// uni.switchTab({
		// 	url: '/pages/index/index'
		// })
		// myRouter('/pages/tabBar/index',true)
	}

	// const 予用户 = async () => {
	// 	const token = userInfo.token
	// 	if (token) {
	// 		const res = await getUserInfo()
	// 		if (res.code === 0) {
	// 			console.log('res.data: ', res.data);
	// 			// await setUserInfo()
	// 		}
	// 	}
	// }

	watch(userInfo, () => {
		console.log('userInfo变化了: ', userInfo);
		console.log('忽略监控: ', 忽略监控);
		if (!忽略监控) {
			console.log("设置缓存ing");
			uni.setStorageSync('userInfo', userInfo)
		}
		忽略监控 = false
		// if (token.value) {
		// 	予用户()
		// } else {
		// 	清空()
		// }
	})

	return {
		注册,
		去登录,
		要登录否,
		清空,
		hasLogin,
		展示用户头像,
		展示用户名,
		userInfo,
		登录,
		退出登录
	}
})